"""
https://stackoverflow.com/questions/33824359/read-file-line-by-line-with-asyncio
https://fastapi.tiangolo.com/advanced/events/ (for asynccontextmanager)
"""

import asyncio
from contextlib import asynccontextmanager
import aiofiles
import io
import time


@asynccontextmanager
async def my_open(path) -> io.TextIOBase:
    print(f'Opening {path}')
    f = await aiofiles.open(path, 'r', encoding='utf8')
    print(f'Opened {path}')
    yield f
    print(f'Closing {path}')
    await f.close()
    print(f'Closed {path}')


if __name__ == '__main__':

    async def main():
        path = r'D:\_dell7590_root\local\LNP_datasets\med\med_dialog\MedDialog_processed\MedDialog_processed\train_data.json'

        async with my_open(path) as f:
            n = 0
            async for line in f:
                if n >= 4:
                    break
                n += 1
                print(n, line)

        n_sleep = 600
        print(f'Sleep for {n_sleep} seconds ...')
        time.sleep(n_sleep)

    print(main())
    asyncio.run(main())
